package com.block.datapush.service.apipush;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.ShiDaiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.db.mapper.MerchantBaseInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * e时贷  回调
 */
@Service
public class ShiDaiPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String phoneMd5 = memberSourceInfo.getMobileMd5();


        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phoneMD5", phoneMd5);
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("monthlySalary", "1");
        bizMap.put("salaryPayMethod", "1");
        bizMap.put("bizPubAccBankDetails", "1");
        bizMap.put("bizBankDetails", "1");
        bizMap.put("bizLicenseYear", "1");
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("overdue", ShiDaiUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("btLimit", ShiDaiUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("hbLimit", ShiDaiUtil.getHuabei(memberSourceInfo.getHuabei()));
        bizMap.put("creditLimit", "1");
        bizMap.put("providentFund", ShiDaiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("loanAmount", ShiDaiUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("sesameCredit", ShiDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("realEstateInfo", ShiDaiUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("carInfo", ShiDaiUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("socialSecurity", ShiDaiUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("insurancePolicy", ShiDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("career", ShiDaiUtil.getGongzuo(memberSourceInfo.getGongzuo()));

        long timestamp = System.currentTimeMillis();

        String clientId = pushApiKeyParam.getApiCode();
        String privateKey = pushApiKeyParam.getApiKey();

        //排序
        String dataJson = getDataJson(clientId, privateKey, bizMap);


        String sign = MD5.create().digestHex(new StringBuilder(dataJson).append(clientId).append(String.valueOf(timestamp)).toString());

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("client-id",clientId);
        headerMap.put("service-code","A0001");
        headerMap.put("sign",sign);
        headerMap.put("timestamp",String.valueOf(timestamp));


        //加密
        String data = new AES(HexUtil.decodeHex(privateKey)).encryptHex(dataJson);


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", data);

        log.info("【e时贷】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-type", "application/json;charset=utf-8")
                .headerMap(headerMap,true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【e时贷】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {
            JSONObject data1 = resultObject.getJSONObject("data");

            String url = data1.getString("url");
            String applyId = data1.getString("applyId");
            pushApiResult.setApproveUrl(url);
            pushApiResult.setOutOrderNo(applyId);
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("applyId", outOrderNo);
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("city", memberSourceInfo.getCity());
       // bizMap.put("bankCard", );
        bizMap.put("idcard", memberSourceInfo.getIdcard());
        bizMap.put("userName", memberSourceInfo.getRealname());
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("monthlySalary", "1");
        bizMap.put("salaryPayMethod", "1");
        bizMap.put("bizPubAccBankDetails", "1");
        bizMap.put("bizBankDetails", "1");
        bizMap.put("bizLicenseYear", "1");
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("overdue", ShiDaiUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("btLimit", ShiDaiUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("hbLimit", ShiDaiUtil.getHuabei(memberSourceInfo.getHuabei()));
        bizMap.put("creditLimit", "1");
        bizMap.put("providentFund", ShiDaiUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("loanAmount", ShiDaiUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("sesameCredit", ShiDaiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("realEstateInfo", ShiDaiUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("carInfo", ShiDaiUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("socialSecurity", ShiDaiUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("insurancePolicy", ShiDaiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("career", ShiDaiUtil.getGongzuo(memberSourceInfo.getGongzuo()));

        long timestamp = System.currentTimeMillis();

        String clientId = pushApiKeyParam.getApiCode();
        String privateKey = pushApiKeyParam.getApiKey();

        //排序
        String dataJson = getDataJson(clientId, privateKey, bizMap);

        String sign = MD5.create().digestHex(new StringBuilder(dataJson).append(clientId).append(String.valueOf(timestamp)).toString());

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("client-id",clientId);
        headerMap.put("service-code","A0002");
        headerMap.put("sign",sign);
        headerMap.put("timestamp",String.valueOf(timestamp));


        //加密
        String data = new AES(HexUtil.decodeHex(privateKey)).encryptHex(dataJson);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", data);


        log.info("【e时贷】导单开始【queryUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json;charset=utf-8")
                .headerMap(headerMap,true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【e时贷】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {
            JSONObject data1 = resultObject.getJSONObject("data");
            String url = data1.getString("url");
            String applyId = data1.getString("applyId");

            pushApiResult.setApproveUrl(url);
            pushApiResult.setOutOrderNo(applyId);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.WAIT_QUERY.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());

        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(pushQueryParam.getOrderNo());

        String requestUrl =pushApiKeyParam.getQueryUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("applyId", pushQueryParam.getOutOrderNo());


        long timestamp = System.currentTimeMillis();

        String clientId = pushApiKeyParam.getApiCode();
        String privateKey = pushApiKeyParam.getApiKey();

        //排序
        String dataJson = getDataJson(clientId, privateKey, bizMap);

        String sign = MD5.create().digestHex(new StringBuilder(dataJson).append(clientId).append(String.valueOf(timestamp)).toString());

        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("client-id",clientId);
        headerMap.put("service-code","A0003");
        headerMap.put("sign",sign);
        headerMap.put("timestamp",String.valueOf(timestamp));

        //加密
        String data = new AES(HexUtil.decodeHex(privateKey)).encryptHex(dataJson);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", data);

        log.info("【e时贷】查询开始【queryUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap),JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json;charset=utf-8")
                .headerMap(headerMap,true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【e时贷】查询结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {
            JSONObject data1 = resultObject.getJSONObject("data");
            String status = data1.getString("status");
            if(StrUtil.equals(String.valueOf(status), "1")){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());


        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) throws Exception {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) throws Exception {

        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    private static <T> String getDataJson(String clientId, String privateKey, T data) {
        //        字段排序
        TreeMap<String, T> treeMap = new TreeMap<String, T>();
        ReflectUtil.getFieldMap(data.getClass()).forEach((k, v) -> {
            treeMap.put(k, (T) ReflectUtil.getFieldValue(data, v));
        });
        //        业务数据
        return JSONObject.toJSONString(treeMap);
    }



}
